home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 10768 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.0 KB  |  67 lines

  1. Path: newshost.lanl.gov!usenet
  2. From: staley@canary.lanl.gov (Martin Staley)
  3. Newsgroups: comp.lang.c++
  4. Subject: Compiler unable to comprehend template for "<<" operator.  What's wrong???
  5. Date: 10 Mar 1996 05:07:01 GMT
  6. Organization: Los Alamos National Laboratory
  7. Distribution: world
  8. Message-ID: <4hto1l$bvl@newshost.lanl.gov>
  9. NNTP-Posting-Host: canary.lanl.gov
  10.  
  11.  
  12. Consider the following code:
  13.  
  14.    #include <iostream.h>
  15.  
  16.    template<class Type>
  17.       class vector {
  18.          Type *v;
  19.          int   size;
  20.          friend ostream &operator<<(ostream &, vector<Type> &);
  21.       };
  22.  
  23.    template<class Type>
  24.       ostream &operator<<(ostream &ostr, vector<Type> &vec) {
  25.       }
  26.  
  27.    main() {
  28.       vector<float> v;
  29.       cout << v;
  30.    }
  31.  
  32. This is an extremely simplified version of some stuff I'm writing.  But
  33. it will not compile.  Both g++ (for the Suns) and Sun c++ give me the
  34. following error:
  35.  
  36.    ld: Undefined symbol 
  37.       ___ls__FR7ostreamRt6vector1Zf
  38.  
  39. Apparently the compiler doesn't know how to use the template for
  40. operator<< to instantiate the << operator for a vector<float>.  WHAT'S
  41. WRONG HERE???  I've tried several minor variations to the above code,
  42. such as saying "class vector<Type> &vec" instead of "vector<Type> &vec"
  43. as the second formal-parameter declaration for the operator<< function.
  44. I've tried it with and without reference arguments.  But nothing seems
  45. to work.  I've also tried writing operator<< as just a regular function
  46. instead of a friend of class vector (though I really want it to be a
  47. friend).  *Then* I get:
  48.  
  49.    In function `int main()':
  50.       no conversion from `vector<float>' to type with default
  51.       `operator <<'
  52.  
  53. Again, the compiler seems unable to build the necessary operator<<.
  54. Things work fine if I write operator<< specifically for floats:
  55.  
  56.    ostream &operator<<(ostream &ostr, vector<float> &vec) {
  57.     ...
  58.    }
  59.  
  60. But if I'm required to do this for every different "vector" type that
  61. I use, then it sort of defeats the purpose of using templates!
  62.  
  63. Can anybody tell me what, if anything, that I am doing wrong above?
  64.  
  65. Martin   staley@cnls.lanl.gov
  66.  
  67.